package org.maxgroundstation.simulation.service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class ClientManager {

	// Static members
	public static final long CLIENT_TIME_LIMIT = 5000L;
	
	// Data members
	private Map<String, Long> clients;
	private Random rand;
	
	ClientManager() {
		clients = new HashMap<String, Long>();
		rand = new Random();
	}
	
	private String createNewClientId() {
    	byte[] clientIDBytes = new byte[8];
    	for (int x = 0; x < clientIDBytes.length; x++) {
    		clientIDBytes[x] = (byte) (rand.nextInt(93) + 33);
    	}
    	return new String(clientIDBytes);
    }
	
	public String createNewClient() {
		long currentTime = System.currentTimeMillis();
		String clientID = createNewClientId();
		clients.put(clientID.trim(), currentTime);
		return clientID;
	}
	
	private boolean hasClient(String clientID) {
		if (clients.keySet().contains(clientID.trim())) return true;
		else return false;
	}
	
	/**
	 * Checks if a client is registered and fresh, and removes them if they are stale.
	 * @param clientID the client's ID string.
	 * @return true if client is registered and fresh.
	 */
	public boolean checkClient(String clientID) {
		boolean result = false;
		if (hasClient(clientID)) {
			long lastUpdate = getLastClientUpdate(clientID);
			long currentTime = System.currentTimeMillis();
			long timeSinceLastUpdate = currentTime - lastUpdate;
			if (timeSinceLastUpdate <= CLIENT_TIME_LIMIT) result = true;
			else {
				result = false;
				clients.remove(clientID);
			}
		}
		return result;
	}
	
	private long getLastClientUpdate(String clientID) {
		long result = -1L;
		if (hasClient(clientID)) result = clients.get(clientID);
		return result;
	}
	
	public void updateClient(String clientID) {
		if (hasClient(clientID)) {
			long currentTime = System.currentTimeMillis();
			clients.put(clientID.trim(), currentTime);
		}
	}
	
	public void clearClients() {
		clients.clear();
	}
}